<template>
  <el-config-provider :locale="appStore.locale" :size="(appStore.size as any)">
    <div class="p-5">
      <!-- 查询条件 -->
      <div class="query-condition flex justify-between">
        <div class="condition">
          <el-input class="w-60 mr-3" v-model="searchInfo.fieldName" placeholder="字段名称"></el-input>
          <el-button type="primary" plain @click="reloadTable">
            <i-ep-Refresh />
          </el-button>
          <el-button type="primary" @click="init">
            <i-ep-Search />
          </el-button>
        </div>
        <div class="button">
          <el-button plain type="primary" @click="downloadField">
            <i-ep-Download class="mr-1" />
            导出字段
          </el-button>
          <el-button plain type="primary" @click="showDialog = true">
            <i-ep-Upload class="mr-1" />
            导入字段
          </el-button>
          <el-button type="primary" @click="createField">
            <i-ep-CirclePlusFilled class="mr-2" />
            新增字段
          </el-button>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-content mt-5">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          :cell-style="cellStyle"
          style="width: 100%"
        >
          <el-table-column align="center" prop="fieldName" label="字段名称"></el-table-column>
          <el-table-column align="center" prop="fieldType" label="字段类别">
            <template #default="{ row }">
              <span
                @click="itemConfig(row)"
                class="text-blue4 cursor-pointer hover:font-bold"
                v-if="getClickFileType(row)"
              >
                {{ row.fieldType }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="fieldShow"
            label="字段说明"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="fieldDesc"
            label="字段描述"
          ></el-table-column>
          <el-table-column align="center" prop="prop" label="操作" width="160">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="editField(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="removeField(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="searchInfo.page"
          v-model:page-size="searchInfo.limit"
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 导入弹窗 -->
    <el-dialog title="导入字段" width="500" v-model="showDialog" :close-on-click-modal="false">
      <div class="p-10">
        <el-form class="flex-center flex-col">
          <el-form-item class="mb-10">
            <el-button type="primary" @click="downloadTemp">
              <i-ep-download class="mr-1" />
              下载模板
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-upload
              accept=".xls,.xlsx"
              ref="upload"
              class="upload-demo w-full"
              action="/"
              :limit="1"
              v-model:file-list="fileList"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">
                  <i-ep-document class="mr-1" />
                  选择文件
                </el-button>
              </template>
              <template #tip>
                <!-- <div class="el-upload__tip text-red">提示</div> -->
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="importField" :loading="loadingBtn">确定导入</el-button>
      </div>
    </el-dialog>

    <!-- 新增字段 -->
    <el-dialog
      :title="currentTableRow ? '编辑字段' : '新增字段'"
      width="500"
      v-model="showDialogAdd"
      :close-on-click-modal="false"
    >
      <div class="p-5">
        <el-form
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          label-position="left"
          ref="ruleFormRef"
          status-icon
        >
          <el-form-item label="字段名称" prop="fieldName">
            <el-input
              @blur="verifyRepeat(1)"
              v-model="ruleForm.fieldName"
              placeholder="请输入字段名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="字段英文" prop="fieldEname">
            <el-input
              @blur="verifyRepeat(2)"
              v-model="ruleForm.fieldEname"
              placeholder="请输入字段英文"
            ></el-input>
          </el-form-item>
          <el-form-item label="字段类型" prop="fieldType">
            <el-select v-model="ruleForm.fieldType" placeholder="请选择字段类型" class="w-full">
              <el-option
                v-for="item in fieldTypeSelect"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字段说明" prop="fieldShow">
            <el-input v-model="ruleForm.fieldShow" placeholder="请输入字段说明"></el-input>
          </el-form-item>
          <el-form-item label="字段描述" prop="fieldDesc">
            <el-input v-model="ruleForm.fieldDesc" placeholder="请输入字段描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialogAdd = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="submit(ruleFormRef)">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 选项字段添加级别 -->
    <el-dialog title="级别添加" width="80%" v-model="showDialogItem" :close-on-click-modal="false">
      <div class="pb-5 flex flex-col">
        <div>
          <el-button type="primary" @click="addTopLevel">添加第一级</el-button>
        </div>
        <div class="table-content mt-5">
          <el-table default-expand-all row-key="id" border :data="tableDataLevel" style="width: 100%">
            <el-table-column align="center" prop="selectCode" label="选项编码"></el-table-column>
            <el-table-column align="center" prop="selectName" label="选项名称"></el-table-column>
            <el-table-column align="center" prop="prop" label="操作">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="removeLevel(row)" plain>删除</el-button>
                <el-button size="small" type="primary" @click="editLevel(row)" plain>编辑</el-button>
                <el-button
                  v-if="currentTableRow.fieldType === '下拉框'"
                  size="small"
                  type="primary"
                  @click="addChildLevel(row)"
                >
                  添加下级
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialogItem = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加一个级别 -->
    <el-dialog
      :title="currentLevelTableRow ? '编辑一级' : '新增一级'"
      width="420"
      v-model="showAddLevel"
    >
      <div class="p-5">
        <el-form
          :model="ruleFormLevel"
          :rules="rulesLevel"
          ref="levelRuleFormRef"
          label-width="80px"
          label-position="left"
          status-icon
        >
          <el-form-item v-if="ruleFormLevel.pid && ruleFormLevel.pid != '0'" label="上级编码">
            <el-input v-model="ruleFormLevel.pselectCode" disabled placeholder="上级编码"></el-input>
          </el-form-item>
          <el-form-item v-if="ruleFormLevel.pid && ruleFormLevel.pid != '0'" label="上级名称">
            <el-input v-model="ruleFormLevel.pselectName" disabled placeholder="上级名称"></el-input>
          </el-form-item>
          <el-form-item label="一级编码" prop="selectCode">
            <el-input v-model="ruleFormLevel.selectCode" placeholder="请输入一级编码"></el-input>
          </el-form-item>
          <el-form-item label="一级名称" prop="selectName">
            <el-input v-model="ruleFormLevel.selectName" placeholder="请输入一级名称"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button :loading="loadingLevelBtn" type="primary" @click="submitLevel(levelRuleFormRef)">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
//@ts-nocheck
import { useAppStore } from '@/store/modules/app';
import { useQueryTable } from '@/utils/hooks/useQueryTable';
import type { UploadUserFile, FormInstance, FormRules } from 'element-plus';
import {
  ledgerFieldTabApi,
  ledgerFieldImportApi,
  ledgerFieldFormApi,
  ledgerFieldDelApi,
  ledgerFieldSelectTabApi,
  ledgerFieldSelectFormApi,
  ledgerFieldSelectDelApi,
  ledgerFieldRepeatApi
} from '@/utils/api/createField';
import XyTools from '@/utils/functions/xy-tools';
import config from '@/utils/config';

const $xy = new XyTools();
const showDialog = ref(false);
const showDialogAdd = ref(false);
const showDialogItem = ref(false);
const showAddLevel = ref(false);
const appStore = useAppStore();
const fileList = ref<UploadUserFile[]>([]); // 字段列表
const fieldTypeSelect = [
  '输入框',
  '下拉框',
  '单选框',
  '复选框',
  '省市区',
  '日期选择',
  '文件上传-最多五个',
  '系统人员单选',
  '系统人员多选',
  '组织名称单选',
  '组织名称多选',
  '数字类型'
]; // 字段类型下拉
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  fieldName: '',
  fieldEname: '',
  fieldDesc: '',
  fieldShow: '',
  fieldType: ''
});
const rules = reactive<FormRules<any>>({
  fieldName: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldEname: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldDesc: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldShow: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldType: [{ required: true, message: '必填项', trigger: 'blur' }]
});
const levelRuleFormRef = ref<FormInstance>();
const ruleFormLevel = reactive({
  selectCode: '',
  selectName: ''
});

// 验证是否已经存在编码
const validatorRepeat = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('必填项'));
  } else {
    if (tableDataLevel.value && tableDataLevel.value.length > 0) {
      const __item = tableDataLevel.value.find((item) => item.selectCode === value);

      if (currentLevelTableRow) {
        if (__item && __item.selectCode !== currentLevelTableRow.selectCode) {
          callback('已存在级别编码');
        }
      } else {
        if (__item) return callback('已存在级别编码');
      }
    }
    callback();
  }
};

const rulesLevel = reactive<FormRules<any>>({
  selectCode: [{ required: true, validator: validatorRepeat, trigger: 'blur' }],
  selectName: [{ required: true, message: '必填项', trigger: 'blur' }]
});
const searchInfoLevel = reactive({
  page: 1,
  limit: 999,
  fieldId: ''
});
const loadingLevelBtn = ref(false);

let currentTableRow = null;
let currentLevelTableRow = null;
let tableDataLevel = ref([]);

// 初始化
const init = async () => {
  loading.value = true;
  const res = await ledgerFieldTabApi(searchInfo);
  loading.value = false;

  if (res.status === 200) {
    tableData.value = res.data;
    total.value = Number(res.count);
  } else {
    ElMessage.error(res.msg);
  }
};

const {
  tableData,
  searchInfo,
  total,
  loading,
  loadingBtn,
  handleSizeChange,
  handleCurrentChange,
  cellStyle
} = useQueryTable(init);

const verifyRepeat = async (type) => {
  if (ruleForm.fieldName) loadingBtn.value = true;
  
  let res;

  if (type === 1) {
    if (!ruleForm.fieldName) return;

    res = await ledgerFieldRepeatApi({ fieldName: ruleForm.fieldName });

    if (res.status !== 200) {
      ElMessage.error(res.msg);

      ruleForm.fieldName = '';
    }
  } else {
    if (!ruleForm.fieldEname) return;

    res = await ledgerFieldRepeatApi({ fieldEname: ruleForm.fieldEname });

    if (res.status !== 200) {
      ElMessage.error(res.msg);
      ruleForm.fieldEname = '';
    }
  }

  loadingBtn.value = false;
};

// 刷新表格
const reloadTable = () => {
  searchInfo.page = 1;
  searchInfo.limit = 10;
  searchInfo.fieldName = '';
  init();
};

// 导出字段
const downloadField = async () => {
  window.open(config.baseUrl + '/cdledger/ledger-field-do/ledgerFieldExport', '__target');
};

// 导入字段
const importField = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error('未选择文件');
    return;
  }

  loadingBtn.value = true;

  const __formData = new FormData();

  __formData.append('file', fileList.value[0].raw as File);

  const res = await ledgerFieldImportApi(__formData);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('已导入');
    showDialog.value = false;
    reloadTable();
  } else {
    ElMessage.error(res.msg);
  }
};

// 下载模板
const downloadTemp = async () => {
  window.open(config.baseUrl + '/cdledger/ledger-field-do/ledgerFieldTemp', '__blank');
};

// 获取是否可以点击的类型
const getClickFileType = (row) => {
  return row.fieldType === '下拉框' || row.fieldType === '单选框' || row.fieldType === '复选框';
};

// 新增字段
const createField = () => {
  currentTableRow = null;
  showDialogAdd.value = true;
  loadingBtn.value = false;

  ruleForm.fieldName = '';
  ruleForm.fieldEname = '';
  ruleForm.fieldDesc = '';
  ruleForm.fieldShow = '';
  ruleForm.fieldType = '';

  if (ruleForm && ruleForm.id) {
    Reflect.deleteProperty(ruleForm, 'id');
  }
};

// 提交
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loadingBtn.value = true;
      const res = await ledgerFieldFormApi(ruleForm);
      loadingBtn.value = false;

      if (res.status === 200) {
        ElMessage.success('操作成功');
        showDialogAdd.value = false;
        reloadTable();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 提交级别
const submitLevel = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loadingLevelBtn.value = true;
      const res = await ledgerFieldSelectFormApi(ruleFormLevel);
      loadingLevelBtn.value = false;

      if (res.status === 200) {
        ElMessage.success('操作成功');
        showAddLevel.value = false;
        initLevelTable();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 删除一项字段
const removeField = (row) => {
  ElMessageBox.confirm('是否确定删除该字段?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await ledgerFieldDelApi({ id: row.id });

      if (res.status === 200) {
        ElMessage.success('已删除');
        init();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 编辑一项字段
const editField = (row) => {
  currentTableRow = row;
  loadingBtn.value = false;

  ruleForm.id = row.id;
  ruleForm.fieldName = row.fieldName;
  ruleForm.fieldEname = row.fieldEname;
  ruleForm.fieldDesc = row.fieldDesc;
  ruleForm.fieldShow = row.fieldShow;
  ruleForm.fieldType = row.fieldType;

  showDialogAdd.value = true;
};

// 配置选项
const itemConfig = async (row) => {
  showDialogItem.value = true;
  searchInfoLevel.fieldId = row.id;
  ruleFormLevel.fieldId = row.id;
  currentTableRow = row;
  initLevelTable();
};

// 级别表格信息
const initLevelTable = async () => {
  const res = await ledgerFieldSelectTabApi(searchInfoLevel);

  if (res.status === 200) {
    tableDataLevel.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 删除一个级别
const removeLevel = (row) => {
  ElMessageBox.confirm(
    currentTableRow.fieldType === '下拉框'
      ? '删除该级别将同时删除对应子级，是否确定删除?'
      : '是否确定删除?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const res = await ledgerFieldSelectDelApi({ id: row.id });

      if (res.status === 200) {
        ElMessage.success('已删除');
        initLevelTable();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 编辑一个级别
const editLevel = (row) => {
  currentLevelTableRow = row;
  ruleFormLevel.selectName = row.selectName;
  ruleFormLevel.selectCode = row.selectCode;
  ruleFormLevel.id = row.id;

  if (row.pid) {
    ruleFormLevel.pid = row.pid;
    ruleFormLevel.pselectCode = row.pselectCode;
    ruleFormLevel.pselectName = row.pselectName;
    showAddLevel.value = true;
  }
};

// 添加第一级
const addTopLevel = () => {
  showAddLevel.value = true;
  loadingLevelBtn.value = false;
  ruleFormLevel.selectCode = '';
  ruleFormLevel.selectName = '';
  currentLevelTableRow = null;

  if (ruleFormLevel.id) {
    Reflect.deleteProperty(ruleFormLevel, 'id');
  }

  if (ruleFormLevel.pid) {
    Reflect.deleteProperty(ruleFormLevel, 'pid');
  }

  if (ruleFormLevel.pselectCode) {
    Reflect.deleteProperty(ruleFormLevel, 'pselectCode');
  }

  if (ruleFormLevel.pselectName) {
    Reflect.deleteProperty(ruleFormLevel, 'pselectName');
  }
};

// 添加子级
const addChildLevel = (row) => {
  showAddLevel.value = true;
  loadingLevelBtn.value = false;
  ruleFormLevel.selectCode = '';
  ruleFormLevel.selectName = '';
  ruleFormLevel.pselectCode = row.selectCode;
  ruleFormLevel.pselectName = row.selectName;
  ruleFormLevel.pid = row.id;
  currentLevelTableRow = null;

  if (ruleFormLevel.id) {
    Reflect.deleteProperty(ruleFormLevel, 'id');
  }
};

searchInfo.fieldName = '';
init();
</script>
